package com.valuegroup.smarttodo.ui.todo.habit;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.valuegroup.smarttodo.R;
import com.valuegroup.smarttodo.common.BaseRecyclerAdapter;
import com.valuegroup.smarttodo.common.BaseViewHolder;
import com.valuegroup.smarttodo.data.ServiceFactory;
import com.valuegroup.smarttodo.data.model.AppStatus;
import com.valuegroup.smarttodo.data.vo.HabitVo;
import com.valuegroup.smarttodo.ui.BaseActivity;
import com.valuegroup.smarttodo.util.AlertUtils;

import java.util.List;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 习惯管理
 * 用于管理习惯项
 */
public class HabitManageActivity extends BaseActivity {


    @BindView(R.id.btnBack)
    ImageButton btnBack;

    @BindView(R.id.btnAdd)
    ImageView btnAdd;

    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;

    private HabitManageAdapter adapter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_habitmanage);
        ButterKnife.bind(this);

        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        adapter = new HabitManageAdapter(this, loadData(), multiTypeSupport);
        recyclerView.setAdapter(adapter);
    }

    @OnClick({R.id.btnBack, R.id.btnAdd})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btnBack:
                finishAfterTransition();
                break;
            case R.id.btnAdd:
                startActivityForResult(new Intent(this, HabitActivity.class), 1002);
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        refreshData(data);
    }

    /**
     * 读取所有数据
     */
    private List<HabitVo> loadData() {
        return ServiceFactory.getInstance().getHabitService().findAllForManage();
    }

    /**
     * 更新列表中某条数据
     * 没有指定的刷新内容时，刷新整个列表
     *
     * @param intent
     */
    private void refreshData(Intent intent) {
        if (intent == null) {
            refreshAllData();
            return;
        }

        long id = intent.getLongExtra(PARAMS_KEY, 0);
        int position = intent.getIntExtra(PARAMS_POSITION, 0);

        if (id == 0) {
            refreshAllData();
            return;
        }

        // 刷新列表中当前操作记录
        HabitVo data = ServiceFactory.getInstance().getHabitService().getHabitVo(id);
        adapter.refreshData(position, data);

        // 平移到指定位置
        recyclerView.smoothScrollToPosition(position);
    }

    /**
     * 更新列表所有数据
     */
    private void refreshAllData() {
        // 刷新列表数据
        adapter.refreshListData(loadData());
        // 平移到相关位置
        recyclerView.smoothScrollToPosition(0);
    }

    @Override
    public void onBackPressed() {
        setCloseParams();
        super.onBackPressed();
    }

    private void setCloseParams() {
        Intent intent = new Intent();
        setResult(RESULT_OK, intent);
    }


    public class HabitManageAdapter extends BaseRecyclerAdapter<HabitVo> {

        private Context context;

        public HabitManageAdapter(Context context, List<HabitVo> data, MultiTypeSupport multiType) {
            super(context, data, multiType);
            this.context = context;
        }

        @Override
        public void bindView(BaseViewHolder v, HabitVo data, int position) {

            // 删除
            ImageView btnDel = v.getView(R.id.btnDel);
            btnDel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    AlertUtils.delDialog(context, R.string.habit, (dialog, which) -> {

                        if (ServiceFactory.getInstance().getHabitService().existOrderRelate(data.getId())) {
                            AlertUtils.showToast(view.getContext(), R.string.exist_relate);
                            return;
                        }

                        ServiceFactory.getInstance().getHabitService().delHabit(data.getId());
                        refreshAllData();
                    });
                }
            });

            // 打开表单
            LinearLayout btnEnter = v.getView(R.id.btnEnter);
            btnEnter.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(view.getContext(), HabitActivity.class);
                    intent.putExtra(PARAMS_KEY, data.getId());
                    intent.putExtra(PARAMS_POSITION, position);
                    startActivityForResult(intent, 1001);
                }
            });

            // 优先级
            ImageView imgQuadrant = v.getView(R.id.tagQuadrant);
            imgQuadrant.setImageResource(AppStatus.QuadrantTagArr[data.getQuadrant()]);

            v.setText(R.id.labTitle, data.getTitle());
            v.setText(R.id.labSubtitle, data.getSubtitle());
            v.setText(R.id.labMinute, String.format(context.getResources().getString(R.string.lab_minute), data.getMinute()));
            //v.setImageResource(R.id.tagEmoji, data.getEmojiResId());
        }
    }


    private BaseRecyclerAdapter.MultiTypeSupport multiTypeSupport = new BaseRecyclerAdapter.MultiTypeSupport<HabitVo>() {
        @Override
        public int getLayoutId(List<HabitVo> datas, int position) {
            if (position == 0) {
                return R.layout.item_default_header;
            } else if (position == (datas.size() + 1)) {
                return R.layout.item_default_bottom;
            } else {
                return R.layout.item_habitmanage;
            }
        }

        @Override
        public int getAppendHeadLayoutSize() {
            return 1;
        }

        @Override
        public int getAppendBottomLayoutSize() {
            return 1;
        }

        @Override
        public boolean isBodyLayout(int dataSize, int position) {
            if (position == 0 || position == (dataSize + 1)) {
                return false;
            } else {
                return true;
            }
        }
    };
}
